<{extend name="Public:public" /}>

<{block name="title"}>动态组件 & 异步组件<{/block}>

<{block name="content"}> 
<div class="content guide with-sidebar components-dynamic-async-guide">
  
<h1>动态组件 &amp; 异步组件</h1>

<h2 id="动态组件"><a href="#动态组件" class="headerlink" title="动态组件" data-scroll="">动态组件</a></h2><p>有的时候，在不同组件之间进行动态切换是非常有用的，比如在一个多标签的界面里：</p>

<div id="dynamic-component-demo" class="demo">
  <button
    v-for="tab in tabs" :key="tab"
    :class="['tab-button', { active: currentTab === tab }]"
    @click="currentTab = tab"
  >{{ tab }}</button>
  <component
    v-bind:is="currentTabComponent"
    class="tab"
  ></component>
</div>

<script>
Vue.component('tab-home', { 
	template: '<div>Home component</div>' 
})
Vue.component('tab-posts', { 
	template: '<div>Posts component</div>' 
})
Vue.component('tab-archive', { 
	template: '<div>Archive component</div>' 
})
new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Home',
    tabs: ['Home', 'Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})
</script>
<style>
.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.tab-button:hover {
  background: #e0e0e0;
}
.tab-button.active {
  background: #e0e0e0;
}
.tab {
  border: 1px solid #ccc;
  padding: 10px;
}
</style>
<code class="prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="tag">&lt;div</span><span class="pln">&nbsp;</span><span class="atn">id</span><span class="pun">=</span><span class="atv">"dynamic-component-demo"</span><span class="pln">&nbsp;</span><span class="atn">class</span><span class="pun">=</span><span class="atv">"demo"</span><span class="tag">&gt;</span></li><li class="L1"><span class="pln">&nbsp;&nbsp;</span><span class="tag">&lt;button</span></li><li class="L2"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="atn">v-for</span><span class="pun">=</span><span class="atv">"tab&nbsp;in&nbsp;tabs"</span><span class="pln">&nbsp;:</span><span class="atn">key</span><span class="pun">=</span><span class="atv">"tab"</span></li><li class="L3"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;:</span><span class="atn">class</span><span class="pun">=</span><span class="atv">"['tab-button',&nbsp;{&nbsp;active:&nbsp;currentTab&nbsp;===&nbsp;tab&nbsp;}]"</span></li><li class="L4"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;@</span><span class="atn">click</span><span class="pun">=</span><span class="atv">"currentTab&nbsp;=&nbsp;tab"</span></li><li class="L5"><span class="pln">&nbsp;&nbsp;</span><span class="tag">&gt;</span><span class="pln">{{&nbsp;tab&nbsp;}}</span><span class="tag">&lt;/button&gt;</span></li><li class="L6"><span class="pln">&nbsp;&nbsp;</span><span class="tag">&lt;component</span></li><li class="L7"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="atn">v-bind:is</span><span class="pun">=</span><span class="atv">"currentTabComponent"</span></li><li class="L8"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="atn">class</span><span class="pun">=</span><span class="atv">"tab"</span></li><li class="L9"><span class="pln">&nbsp;&nbsp;</span><span class="tag">&gt;&lt;/component&gt;</span></li><li class="L0"><span class="tag">&lt;/div&gt;</span></li><li class="L1"><span class="pln">&nbsp;</span></li><li class="L2"><span class="tag">&lt;script&gt;</span></li><li class="L3"><span class="typ">Vue</span><span class="pun">.</span><span class="pln">component</span><span class="pun">(</span><span class="str">'tab-home'</span><span class="pun">,</span><span class="pln">&nbsp;</span><span class="pun">{</span><span class="pln">&nbsp;</span></li><li class="L4"><span class="pln">&nbsp;&nbsp;template</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="str">'&lt;div&gt;Home&nbsp;component&lt;/div&gt;'</span><span class="pln">&nbsp;</span></li><li class="L5"><span class="pun">})</span></li><li class="L6"><span class="typ">Vue</span><span class="pun">.</span><span class="pln">component</span><span class="pun">(</span><span class="str">'tab-posts'</span><span class="pun">,</span><span class="pln">&nbsp;</span><span class="pun">{</span><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">&nbsp;&nbsp;template</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="str">'&lt;div&gt;Posts&nbsp;component&lt;/div&gt;'</span><span class="pln">&nbsp;</span></li><li class="L8"><span class="pun">})</span></li><li class="L9"><span class="typ">Vue</span><span class="pun">.</span><span class="pln">component</span><span class="pun">(</span><span class="str">'tab-archive'</span><span class="pun">,</span><span class="pln">&nbsp;</span><span class="pun">{</span><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">&nbsp;&nbsp;template</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="str">'&lt;div&gt;Archive&nbsp;component&lt;/div&gt;'</span><span class="pln">&nbsp;</span></li><li class="L1"><span class="pun">})</span></li><li class="L2"><span class="kwd">new</span><span class="pln">&nbsp;</span><span class="typ">Vue</span><span class="pun">({</span></li><li class="L3"><span class="pln">&nbsp;&nbsp;el</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="str">'#dynamic-component-demo'</span><span class="pun">,</span></li><li class="L4"><span class="pln">&nbsp;&nbsp;data</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="pun">{</span></li><li class="L5"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;currentTab</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="str">'Home'</span><span class="pun">,</span></li><li class="L6"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;tabs</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="pun">[</span><span class="str">'Home'</span><span class="pun">,</span><span class="pln">&nbsp;</span><span class="str">'Posts'</span><span class="pun">,</span><span class="pln">&nbsp;</span><span class="str">'Archive'</span><span class="pun">]</span></li><li class="L7"><span class="pln">&nbsp;&nbsp;</span><span class="pun">},</span></li><li class="L8"><span class="pln">&nbsp;&nbsp;computed</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="pun">{</span></li><li class="L9"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;currentTabComponent</span><span class="pun">:</span><span class="pln">&nbsp;</span><span class="kwd">function</span><span class="pln">&nbsp;</span><span class="pun">()</span><span class="pln">&nbsp;</span><span class="pun">{</span></li><li class="L0"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="kwd">return</span><span class="pln">&nbsp;</span><span class="str">'tab-'</span><span class="pln">&nbsp;</span><span class="pun">+</span><span class="pln">&nbsp;</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">currentTab</span><span class="pun">.</span><span class="pln">toLowerCase</span><span class="pun">()</span></li><li class="L1"><span class="pln">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="pun">}</span></li><li class="L2"><span class="pln">&nbsp;&nbsp;</span><span class="pun">}</span></li><li class="L3"><span class="pun">})</span></li><li class="L4"><span class="tag">&lt;/script&gt;</span><span class="pln"> </span></li></ol></code>



<p>上述内容可以通过 Vue 的 <code>&lt;component&gt;</code> 元素加一个特殊的 <code>is</code> 特性来实现：</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 组件会在 `currentTabComponent` 改变时改变 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">component</span> <span class="attr">v-bind:is</span>=<span class="string">"currentTabComponent"</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<p>在上述示例中，<code>currentTabComponent</code> 可以包括</p>
<ul>
<li>已注册组件的名字，或</li>
<li>一个组件的选项对象</li>
</ul>
<p>你可以在<a href="https://jsfiddle.net/chrisvfritz/o3nycadu/" target="_blank" rel="noopener">这里</a>查阅并体验完整的代码，或在<a href="https://jsfiddle.net/chrisvfritz/b2qj69o1/" target="_blank" rel="noopener">这个版本</a>了解绑定组件选项对象，而不是已注册组件名的示例。</p>



<h3 id="解析-DOM-模板时的注意事项"> 
	<a href="#解析-DOM-模板时的注意事项" class="headerlink" title="解析-DOM-模板时的注意事项" data-scroll="">is 解析-DOM-模板时的注意事项</a> 
</h3>
<p>有些 HTML 元素，诸如 <code>&lt;ul&gt;</code>、<code>&lt;ol&gt;</code>、<code>&lt;table&gt;</code> 和 <code>&lt;select&gt;</code>，对于哪些元素可以出现在其内部是有严格限制的。而有些元素，诸如 <code>&lt;li&gt;</code>、<code>&lt;tr&gt;</code> 和 <code>&lt;option&gt;</code>，只能出现在其它某些特定的元素内部。</p>
<p>这会导致我们使用这些有约束条件的元素时遇到一些问题。例如：</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">table</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">blog-post-row</span>&gt;</span><span class="tag">&lt;/<span class="name">blog-post-row</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">table</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<p>这个自定义组件 <code>&lt;blog-post-row&gt;</code> 会被作为无效的内容提升到外部，并导致最终渲染结果出错。幸好这个特殊的 <code>is</code> 特性给了我们一个变通的办法：</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">table</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">tr</span> <span class="attr">is</span>=<span class="string">"blog-post-row"</span>&gt;</span><span class="tag">&lt;/<span class="name">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">table</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<p>需要注意的是<strong>如果我们从以下来源使用模板的话，这条限制是<em>不存在</em>的</strong>：</p>
<ul>
<li>字符串 (例如：<code>template: '...'</code>)</li>
<li><a href="single-file-components.html">单文件组件 (<code>.vue</code>)</a></li>
<li><a href="components-edge-cases.html#X-Templates"><code>&lt;script type="text/x-template"&gt;</code></a></li>
</ul>


  
<h2 id="在动态组件上使用-keep-alive">
	<a href="#在动态组件上使用-keep-alive" class="headerlink" title="在动态组件上使用 keep-alive" data-scroll="">在动态组件上使用 <code>keep-alive</code></a>
</h2>
<blockquote>
	<div>van: 一般用于 &lt;router-view&gt;&lt;/router-view&gt;</div>
</blockquote>

<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">keep-alive exclude="Detail"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">router-view</span> /&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">/keep-alive</span>&gt;</span><br></pre></td></tr></tbody></table></figure>
<p>// <code>mouted钩子</code> 不会生效, 除了<code>exclude</code>对应的组件</p>
<p>// <code>activated钩子</code> 会生效, 此钩子是专门针对 <code>&lt;keep-alive&gt;</code>设计的</p>
<br>
<br>

<p>我们之前曾经在一个多标签的界面中使用 <code>is</code> 特性来切换不同的组件：</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">component</span> <span class="attr">v-bind:is</span>=<span class="string">"currentTabComponent"</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<p>当在这些组件之间切换的时候，你有时会想保持这些组件的状态，以避免反复重渲染导致的性能问题。例如我们来展开说一说这个多标签界面：</p>

<div id="dynamic-component-demo" class="demo"><button class="dynamic-component-demo-tab-button dynamic-component-demo-active">Posts</button><button class="dynamic-component-demo-tab-button">Archive</button> <div class="dynamic-component-demo-posts-tab dynamic-component-demo-tab"><ul class="dynamic-component-demo-posts-sidebar"><li class="">          Cat Ipsum        </li><li class="">          Hipster Ipsum        </li><li class="">          Cupcake Ipsum        </li></ul> <div class="dynamic-component-demo-post-container"><strong>          Click on a blog title to the left to view it.        </strong></div></div></div>
<script>
Vue.component('tab-posts', {
  data: function () {
    return {
      posts: [
        {
          id: 1,
          title: 'Cat Ipsum',
          content: '<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>'
        },
        {
          id: 2,
          title: 'Hipster Ipsum',
          content: '<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>'
        },
        {
          id: 3,
          title: 'Cupcake Ipsum',
          content: '<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>'
        }
      ],
      selectedPost: null
    }
  },
  template: '\
    <div class="dynamic-component-demo-posts-tab">\
      <ul class="dynamic-component-demo-posts-sidebar">\
        <li\
          v-for="post in posts"\
          v-bind:key="post.id"\
          v-bind:class="{ \'dynamic-component-demo-active\': post === selectedPost }"\
          v-on:click="selectedPost = post"\
        >\
          {{ post.title }}\
        </li>\
      </ul>\
      <div class="dynamic-component-demo-post-container">\
        <div \
          v-if="selectedPost"\
          class="dynamic-component-demo-post"\
        >\
          <h3>{{ selectedPost.title }}</h3>\
          <div v-html="selectedPost.content"></div>\
        </div>\
        <strong v-else>\
          Click on a blog title to the left to view it.\
        </strong>\
      </div>\
    </div>\
  '
})
Vue.component('tab-archive', {
  template: '<div>Archive component</div>'
})
new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})
</script>
<style>
.dynamic-component-demo-tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.dynamic-component-demo-tab-button:hover {
  background: #e0e0e0;
}
.dynamic-component-demo-tab-button.dynamic-component-demo-active {
  background: #e0e0e0;
}
.dynamic-component-demo-tab {
  border: 1px solid #ccc;
  padding: 10px;
}
.dynamic-component-demo-posts-tab {
  display: flex;
}
.dynamic-component-demo-posts-sidebar {
  max-width: 40vw;
  margin: 0 !important;
  padding: 0 10px 0 0 !important;
  list-style-type: none;
  border-right: 1px solid #ccc;
}
.dynamic-component-demo-posts-sidebar li {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  cursor: pointer;
}
.dynamic-component-demo-posts-sidebar li:hover {
  background: #eee;
}
.dynamic-component-demo-posts-sidebar li.dynamic-component-demo-active {
  background: lightblue;
}
.dynamic-component-demo-post-container {
  padding-left: 10px;
}
.dynamic-component-demo-post > :first-child {
  margin-top: 0 !important;
  padding-top: 0 !important;
}
</style>

<p>你会注意到，如果你选择了一篇文章，切换到 <em>Archive</em> 标签，然后再切换回 <em>Posts</em>，是不会继续展示你之前选择的文章的。这是因为你每次切换新标签的时候，Vue 都创建了一个新的 <code>currentTabComponent</code> 实例。</p>
<p>重新创建动态组件的行为通常是非常有用的，但是在这个案例中，我们更希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题，我们可以用一个 <code>&lt;keep-alive&gt;</code> 元素将其动态组件包裹起来。</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 失活的组件将会被缓存！--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">keep-alive</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">component</span> <span class="attr">v-bind:is</span>=<span class="string">"currentTabComponent"</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">keep-alive</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<p>来看看修改后的结果：</p>

<div id="dynamic-component-keep-alive-demo" class="demo"><button class="dynamic-component-demo-tab-button dynamic-component-demo-active">Posts</button><button class="dynamic-component-demo-tab-button">Archive</button> <div class="dynamic-component-demo-posts-tab dynamic-component-demo-tab"><ul class="dynamic-component-demo-posts-sidebar"><li class="">          Cat Ipsum        </li><li class="">          Hipster Ipsum        </li><li class="">          Cupcake Ipsum        </li></ul> <div class="dynamic-component-demo-post-container"><strong>          Click on a blog title to the left to view it.        </strong></div></div></div>
<script>
new Vue({
  el: '#dynamic-component-keep-alive-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})
</script>

<p>现在这个 <em>Posts</em> 标签保持了它的状态 (被选中的文章) 甚至当它未被渲染时也是如此。你可以在<a href="https://jsfiddle.net/chrisvfritz/Lp20op9o/" target="_blank" rel="noopener">这个 fiddle</a> 查阅到完整的代码。</p>
<p class="tip">注意这个 <code>&lt;keep-alive&gt;</code> 要求被切换到的组件都有自己的名字，不论是通过组件的 <code>name</code> 选项还是局部/全局注册。</p>

<p>你可以在 <a href="../api/#keep-alive">API 参考文档</a> 查阅更多关于 <code>&lt;keep-alive&gt;</code> 的细节。</p>
<h2 id="异步组件"><a href="#异步组件" class="headerlink" title="异步组件" data-scroll="">异步组件</a></h2><p>在大型应用中，我们可能需要将应用分割成小一些的代码块，并且只在需要的时候才从服务器加载一个模块。为了简化，Vue 允许你以一个工厂函数的方式定义你的组件，这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数，且会把结果缓存起来供未来重渲染。例如：</p>
<figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line">Vue.component(<span class="string">'async-example'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>{</span><br><span class="line">  setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line">    <span class="comment">// 向 `resolve` 回调传递组件定义</span></span><br><span class="line">    resolve({</span><br><span class="line">      template: <span class="string">'&lt;div&gt;I am async!&lt;/div&gt;'</span></span><br><span class="line">    })</span><br><span class="line">  }, <span class="number">1000</span>)</span><br><span class="line">})</span><br></pre></td></tr></tbody></table></figure>
<p>如你所见，这个工厂函数会收到一个 <code>resolve</code> 回调，这个回调函数会在你从服务器得到组件定义的时候被调用。你也可以调用 <code>reject(reason)</code> 来表示加载失败。这里的 <code>setTimeout</code> 是为了演示用的，如何获取组件取决于你自己。一个推荐的做法是将异步组件和 <a href="https://webpack.js.org/guides/code-splitting/" target="_blank" rel="noopener">webpack 的 code-splitting 功能</a>一起配合使用：</p>
<figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line">Vue.component(<span class="string">'async-webpack-example'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>{</span><br><span class="line"> &nbsp;<span class="comment">// 这个特殊的 `require` 语法将会告诉 webpack</span></span><br><span class="line">  <span class="comment">// 自动将你的构建代码切割成多个包，这些包</span></span><br><span class="line">  <span class="comment">// 会通过 Ajax 请求加载</span></span><br><span class="line">  <span class="built_in">require</span>([<span class="string">'./my-async-component'</span>], resolve)</span><br><span class="line">})</span><br></pre></td></tr></tbody></table></figure>
<p>你也可以在工厂函数中返回一个 <code>Promise</code>，所以把 webpack 2 和 ES2015 语法加在一起，我们可以写成这样：</p>
<figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line">Vue.component(</span><br><span class="line">  <span class="string">'async-webpack-example'</span>,</span><br><span class="line">  <span class="comment">// 这个 `import` 函数会返回一个 `Promise` 对象。</span></span><br><span class="line">  () =&gt; <span class="keyword">import</span>(<span class="string">'./my-async-component'</span>)</span><br><span class="line">)</span><br></pre></td></tr></tbody></table></figure>
<p>当使用<a href="components.html#本地注册">局部注册</a>的时候，你也可以直接提供一个返回 <code>Promise</code> 的函数：</p>
<figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Vue({</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  components: {</span><br><span class="line">    <span class="string">'my-component'</span>: <span class="function"><span class="params">()</span> =&gt;</span> <span class="keyword">import</span>(<span class="string">'./my-async-component'</span>)</span><br><span class="line">  }</span><br><span class="line">})</span><br></pre></td></tr></tbody></table></figure>
<p class="tip">如果你是一个 <strong>Browserify</strong> 用户同时喜欢使用异步组件，很不幸这个工具的作者<a href="https://github.com/substack/node-browserify/issues/58#issuecomment-21978224" target="_blank" rel="noopener">明确表示</a>异步加载“并不会被 Browserify 支持”，至少官方不会。Browserify 社区已经找到了<a href="https://github.com/vuejs/vuejs.org/issues/620" target="_blank" rel="noopener">一些变通方案</a>，这些方案可能会对已存在的复杂应用有帮助。对于其它的场景，我们推荐直接使用 webpack，以拥有内建的被作为第一公民的异步支持。</p> 

<h3 id="处理加载状态"><a href="#处理加载状态" class="headerlink" title="处理加载状态" data-scroll="">处理加载状态</a></h3><blockquote>
<p>2.3.0+ 新增</p>
</blockquote>
<p>这里的异步组件工厂函数也可以返回一个如下格式的对象：</p>
<figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> AsyncComponent = <span class="function"><span class="params">()</span> =&gt;</span> ({</span><br><span class="line">  <span class="comment">// 需要加载的组件 (应该是一个 `Promise` 对象)</span></span><br><span class="line">  component: <span class="keyword">import</span>(<span class="string">'./MyComponent.vue'</span>),</span><br><span class="line">  <span class="comment">// 异步组件加载时使用的组件</span></span><br><span class="line">  loading: LoadingComponent,</span><br><span class="line">  <span class="comment">// 加载失败时使用的组件</span></span><br><span class="line">  error: ErrorComponent,</span><br><span class="line">  <span class="comment">// 展示加载时组件的延时时间。默认值是 200 (毫秒)</span></span><br><span class="line">  delay: <span class="number">200</span>,</span><br><span class="line">  <span class="comment">// 如果提供了超时时间且组件加载也超时了，</span></span><br><span class="line">  <span class="comment">// 则使用加载失败时使用的组件。默认值是：`Infinity`</span></span><br><span class="line">  timeout: <span class="number">3000</span></span><br><span class="line">})</span><br></pre></td></tr></tbody></table></figure>
<blockquote>
<p>注意如果你希望在 <a href="https://github.com/vuejs/vue-router" target="_blank" rel="noopener">Vue Router</a> 的路由组件中使用上述语法的话，你必须使用 Vue Router 2.4.0+ 版本。</p>
</blockquote>

  
  
    <div class="guide-links">
      
      
        <span>← <a href="/v2/guide/components-slots.html">插槽</a></span>
      
      
      
        <span style="float: right;"><a href="/v2/guide/components-edge-cases.html">处理边界情况</a> →</span>
      
    </div>
  
  <div class="footer">
<div class="bsa-cpc"></div>
<script>
  (function(){
    if(typeof _bsa !== 'undefined' && _bsa) {
    _bsa.init('default', 'CKYD62QM', 'placement:vuejsorg', {
      target: '.bsa-cpc',
      align: 'horizontal',
      disable_css: 'true'
    });
      }
  })();
</script>

    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/components-dynamic-async.md" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>
<{/block}>
